package io;

  

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;

import com.google.gson.Gson;

public class Serialize {
	static Gson g=new Gson();
	public static void main(String[] args) throws IOException {
		Writable write=new IntWritable(10);
		byte[] test=serialize(write);
		byte[] newb={100,20,3,0};
		System.out.println(g.toJson(test));
		deSerialize(write,newb);
		System.out.println(g.toJson(write));
 	}
	
	/**
	 * 序列号对象
	 * @param writable
	 * @return
	 * @throws IOException
	 */
	public static byte[] serialize(Writable writable) throws IOException  {
		ByteArrayOutputStream out =new ByteArrayOutputStream();
		DataOutputStream dataout=new DataOutputStream(out);
		writable.write(  dataout);
		dataout.close();
		return out.toByteArray();
	}
	/**
	 * 反序列号对象
	 * @param writable
	 * @return
	 * @throws IOException
	 */
	public static byte[] deSerialize(Writable writable,byte[] bytes) throws IOException  {
		ByteArrayInputStream in =new ByteArrayInputStream(bytes);
		DataInputStream datain=new DataInputStream(in);
		writable.readFields(datain);
		datain.close();
		return bytes;
	}
 }
